package com.dfcj.oauth2security.configure;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.FilterInvocation;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.WebServiceProvider;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;

@Slf4j
@Service
public class MyAccessDecisionManager implements AccessDecisionManager {
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributeCollection)
            throws AccessDeniedException, InsufficientAuthenticationException{
        HttpServletRequest httpRequest = ((FilterInvocation)object).getHttpRequest();
        StringBuffer stringBuffer=new StringBuffer();
        authentication.getAuthorities().stream().forEach(s->stringBuffer.append(s));
        log.info("Authentication information:"+stringBuffer);
        log.info("url information:"+httpRequest.getRequestURI());
        StringBuffer stringBufferConfigAttributeCollection=new StringBuffer();
        authentication.getAuthorities().stream().forEach(s->stringBufferConfigAttributeCollection.append(s));
        log.info("configAttributeCollection information:"+stringBufferConfigAttributeCollection);
        if(httpRequest.getRequestURI().equals("/hello/test")){
            return;
        }
        /**
         * 测试证明PreAuthorize还是会参与权限判断，但是可以通过decide去做了
         * 不需要使用PreAuthorize再去做一次
         */
        if(httpRequest.getRequestURI().equals("/hello")){
            return;
        }
        throw new AccessDeniedException("AccessDecisionManager Access Denied");
    }

    public boolean supports(ConfigAttribute var1){
        return true;
    }

    public boolean supports(Class<?> var1){
        return true;
    }
}
